#!/bin/bash

# variable

REDIS_DOWNLOAD_URL="https://download.redis.io/releases/redis-6.2.6.tar.gz"
PACKAGE_NAME="redis.tar.gz" # 包名
REDIS_PACKAGE_NAME="redis" # redis包名
INSTALL_PATH="/usr/local" # redis安装目录
AUTO_INIT_PATH="/etc/init.d" # 自启动目录

cd ${INSTALL_PATH}

echo "开始下载redis包"

sudo wget -O ${PACKAGE_NAME} ${REDIS_DOWNLOAD_URL}

echo "开始解压redis包"

#http://www.javashuo.com/article/p-phgplnio-bn.html
sudo mkdir ${REDIS_PACKAGE_NAME} && sudo tar -zxvf ${PACKAGE_NAME} -C ${REDIS_PACKAGE_NAME} --strip-components 1 && cd ${REDIS_PACKAGE_NAME}

echo "执行安装redis"

sudo make && sudo make install


echo "删除安装包${PACKAGE_NAME}"

sudo rm -rf ${INSTALL_PATH}/${PACKAGE_NAME}

# 进入redis安装目录/utils
cd ${INSTALL_PATH}/${REDIS_PACKAGE_NAME}/utils/

# 拷贝redis自启动文件
echo "开始设置开机自启动"
sudo cp redis_init_script ${AUTO_INIT_PATH}/redis

sudo cd ${AUTO_INIT_PATH}

# 使用sed命令替换文本，文本中含有“/”的处理方法 
# https://blog.csdn.net/qq_55723966/article/details/117667358?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-117667358-blog-17269645.pc_relevant_3mothn_strategy_recovery&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-117667358-blog-17269645.pc_relevant_3mothn_strategy_recovery&utm_relevant_index=2
sudo sed -i "s#/usr/local/bin/redis-server#${INSTALL_PATH}/${REDIS_PACKAGE_NAME}/src/redis-server#g" redis

sudo sed -i "s#/usr/local/bin/redis-cli#${INSTALL_PATH}/${REDIS_PACKAGE_NAME}/src/redis-cli#g" redis
# 设置对应端口配置文件
sudo mkdir /etc/redis &&  cp ${INSTALL_PATH}/${REDIS_PACKAGE_NAME}/redis.conf /etc/redis/6379.conf
sudo sed -i 's/daemonize no/daemonize yes/g' /etc/redis/6379.conf
sudo chmod a+x  ${AUTO_INIT_PATH}/redis 

# 重新载入配置  systemctl daemon-reload
sudo systemctl daemon-reload
sudo service redis start

